<template>
  <div class="space-y-6">
    <el-card class="shadow-sm">
      <el-tabs v-model="activeTab" class="min-h-[600px]">
        <el-tab-pane label="字典类型" name="type">
          <div class="space-y-6">
            <div class="flex items-center justify-between mb-4">
              <span class="text-xl font-semibold text-gray-800">字典类型管理</span>
              <el-button type="primary" @click="handleAddType" class="px-4 py-2">
                <el-icon class="mr-1">
                  <Plus />
                </el-icon>新增类型
              </el-button>
            </div>
            <DictStatusSearch
              dict-code="sys_status"
              @search="handleTypeSearch"
              @reset="handleTypeReset"
            />

            <div class="overflow-x-auto">
              <el-table :data="dictTypeList" v-loading="loading" border class="text-sm">
                <el-table-column prop="code" label="字典类型编码" min-width="150" />
                <el-table-column prop="name" label="字典类型名称" min-width="150" />
                <el-table-column prop="description" label="描述" min-width="200" />
                <el-table-column prop="status" label="状态" width="80">
                  <template #default="{ row }">
                    <DictTag
                      dict-type="sys_status"
                      :value="row.status"
                      size="small"
                      custom-class="text-xs px-2 py-1"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="createTime"
                  label="创建时间"
                  width="180"
                  :formatter="tableDateTimeFormatter"
                />
                <el-table-column label="操作" width="160" fixed="right">
                  <template #default="{ row }">
                    <div class="flex space-x-2">
                      <el-button
                        type="primary"
                        size="small"
                        @click="handleEditType(row)"
                        class="px-3 py-1"
                      >
                        <el-icon class="mr-1">
                          <Edit />
                        </el-icon>编辑
                      </el-button>
                      <el-button
                        type="danger"
                        size="small"
                        @click="handleDeleteType(row)"
                        class="px-3 py-1"
                      >
                        <el-icon class="mr-1">
                          <Delete />
                        </el-icon>删除
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="字典数据" name="data">
          <div class="space-y-6">
            <div class="flex items-center justify-between mb-4">
              <span class="text-xl font-semibold text-gray-800">字典数据管理</span>
              <div class="flex items-center space-x-4">
                <el-select
                  v-model="selectedType"
                  placeholder="选择字典类型"
                  class="w-48"
                  @change="loadDictData"
                >
                  <el-option
                    v-for="type in dictTypeList"
                    :key="type.code"
                    :label="type.name"
                    :value="type.code"
                  />
                </el-select>
                <el-button type="primary" @click="handleAddData" class="px-4 py-2">
                  <el-icon class="mr-1">
                    <Plus />
                  </el-icon>新增数据
                </el-button>
              </div>
            </div>
            <DictStatusSearch
              dict-code="sys_status"
              @search="handleDataSearch"
              @reset="handleDataReset"
            />

            <div class="overflow-x-auto">
              <el-table :data="dictDataList" v-loading="dataLoading" border class="text-sm">
                <el-table-column prop="label" label="标签名" min-width="150" />
                <el-table-column prop="value" label="数据值" min-width="150" />
                <el-table-column prop="sort" label="排序" width="80" />
                <el-table-column prop="status" label="状态" width="80">
                  <template #default="{ row }">
                    <DictTag
                      dict-type="sys_status"
                      :value="row.status"
                      size="small"
                      custom-class="text-xs px-2 py-1"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="160" fixed="right">
                  <template #default="{ row }">
                    <div class="flex space-x-2">
                      <el-button
                        type="primary"
                        size="small"
                        @click="handleEditData(row)"
                        class="px-3 py-1"
                      >
                        <el-icon class="mr-1">
                          <Edit />
                        </el-icon>编辑
                      </el-button>
                      <el-button
                        type="danger"
                        size="small"
                        @click="handleDeleteData(row)"
                        class="px-3 py-1"
                      >
                        <el-icon class="mr-1">
                          <Delete />
                        </el-icon>删除
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 字典类型表单对话框 -->
    <DictTypeFormDialog
      v-model="typeDialogVisible"
      :type-data="currentType"
      @success="handleTypeSuccess"
    />

    <!-- 字典数据表单对话框 -->
    <DictDataFormDialog
      v-model="dataDialogVisible"
      :data-data="currentData"
      :dict-types="dictTypeList"
      @success="handleDataSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getDictTypeList,
  deleteDictType,
  getDictDataList,
  deleteDictData,
  getDictDataByType,
} from "@/api/dict";
import DictTypeFormDialog from "@/components/DictTypeFormDialog.vue";
import DictDataFormDialog from "@/components/DictDataFormDialog.vue";
import DictStatusSearch from "@/components/DictStatusSearch.vue";
import DictTag from "@/components/DictTag.vue";

import { tableDateTimeFormatter } from "@/utils/format";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";

const activeTab = ref("type");
const loading = ref(false);
const dataLoading = ref(false);
const dictTypeList = ref([]);
const dictDataList = ref([]);
const selectedType = ref("");

const typeDialogVisible = ref(false);
const dataDialogVisible = ref(false);
const currentType = ref(null);
const currentData = ref(null);
const typeSearchForm = ref({ status: null });
const dataSearchForm = ref({ status: null });

const loadDictTypes = async () => {
  loading.value = true;
  try {
    const params = { ...typeSearchForm.value };
    const data = await getDictTypeList(params);
    dictTypeList.value = data.list || [];
  } catch (error) {
    ElMessage.error("获取字典类型失败");
  } finally {
    loading.value = false;
  }
};

const loadDictData = async () => {
  if (!selectedType.value) return;

  dataLoading.value = true;
  try {
    const params = { code: selectedType.value, ...dataSearchForm.value };
    const data = await getDictDataByType(params);
    dictDataList.value = data || [];
  } catch (error) {
    ElMessage.error("获取字典数据失败");
  } finally {
    dataLoading.value = false;
  }
};

const handleAddType = () => {
  currentType.value = null;
  typeDialogVisible.value = true;
};

const handleEditType = (row) => {
  currentType.value = { ...row };
  typeDialogVisible.value = true;
};

const handleDeleteType = async (row) => {
  try {
    await ElMessageBox.confirm("确定要删除该字典类型吗？", "提示");
    await deleteDictType(row.id);
    ElMessage.success("删除成功");
    loadDictTypes();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const handleAddData = () => {
  if (!selectedType.value) {
    ElMessage.warning('请先选择字典类型');
    return;
  }
  
  // 将当前选中的字典类型ID作为初始值传递给弹框，但不设置整个对象以避免误判为编辑模式
  const selectedDictType = dictTypeList.value.find(type => type.code === selectedType.value);
  if (selectedDictType) {
    // 使用一个特殊标记来区分新增和编辑模式
    currentData.value = { 
      _isAdd: true, // 标记为新增模式
      dictTypeId: selectedDictType.id 
    };
  } else {
    currentData.value = null;
  }
  dataDialogVisible.value = true;
};

const handleEditData = (row) => {
  currentData.value = { ...row };
  dataDialogVisible.value = true;
};

const handleDeleteData = async (row) => {
  try {
    await ElMessageBox.confirm("确定要删除该字典数据吗？", "提示");
    await deleteDictData(row.id);
    ElMessage.success("删除成功");
    loadDictData();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const handleTypeSuccess = () => {
  typeDialogVisible.value = false;
  loadDictTypes();
};

const handleDataSuccess = () => {
  dataDialogVisible.value = false;
  loadDictData();
};

const handleTypeSearch = (params) => {
  Object.assign(typeSearchForm.value, params);
  loadDictTypes();
};

const handleTypeReset = (params) => {
  Object.assign(typeSearchForm.value, params);
  loadDictTypes();
};

const handleDataSearch = (params) => {
  Object.assign(dataSearchForm.value, params);
  loadDictData();
};

const handleDataReset = (params) => {
  Object.assign(dataSearchForm.value, params);
  loadDictData();
};

onMounted(() => {
  loadDictTypes();
});
</script>

<style scoped>
/* 使用Tailwind CSS替代原有样式 */
</style>